package com.ruyuan2020.furnishing.common.controller;

import com.scholar.sdk.dashboard.DashboardVo;
import com.scholar.sdk.dashboard.IMonitorDataController;
import com.scholar.sdk.utils.RollingWindow;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(IMonitorDataController.URI)
public class MonitorDataController implements IMonitorDataController {

    @Autowired
    private MeterRegistry meterRegistry;

    @Autowired
    private RollingWindow rollingWindow;

    @Value("${spring.application.name}")
    private String applicationName;

    @Override
    @GetMapping
    public DashboardVo exportMonitorInfo() {
        DashboardVo vo = new DashboardVo();
//        Gauge dubboMaxGauge = meterRegistry.find("dubbo.thread.pool.max.size").gauge();
        Gauge dubboActiveGauge = meterRegistry.find("dubbo.thread.pool.active.size").gauge();
        double dubboActive = dubboActiveGauge != null ? dubboActiveGauge.value() : 0;
//        Gauge tomcatMaxGauge = meterRegistry.find("tomcat.threads.config.max").gauge();
        Gauge tomcatActiveGauge = meterRegistry.find("tomcat.threads.busy").gauge();
        double tomcatActive = tomcatActiveGauge != null ? tomcatActiveGauge.value() : 0;
//        Gauge connectionMaxGauge = meterRegistry.find("jdbc.connections.max").gauge();
        Gauge connectionActiveGauge = meterRegistry.find("jdbc.connections.active").gauge();
        double connectionActive = connectionActiveGauge != null ? connectionActiveGauge.value() : 0;

//        Gauge cpu = meterRegistry.find("system.cpu.usage").gauge();
//        Gauge memory = meterRegistry.find("jvm.memory.used").gauge();

        vo.addKvElement(applicationName + "-TPS", String.valueOf(rollingWindow.getCurrentQps()), DashboardVo.AGGR_TYPE_SUM);

        vo.addLineChartElement(applicationName + "-线程/连接",
                DashboardVo.lineChart(
                        "Tomcat 线程", String.valueOf(tomcatActive),
                        "Dubbo 线程", String.valueOf(dubboActive),
                        "数据库连接", String.valueOf(connectionActive)
                ),
                DashboardVo.AGGR_TYPE_SUM);
        return vo;
    }
}